import get from 'lodash-es/get.js';
import set from 'lodash-es/set.js';

export default {
  install(app) {
    try {
      Object.defineProperty(window, '__GLOBAL_VUE_APP', {
        value: app,
        enumerable: false,
        configurable: false,
        writable: false,
      });

      const versionStr = get(window.__GLOBAL_VUE_APP, 'version') || '';
      const version = Number(versionStr.split('.')[0]);
      if (version < 3) {
        set(window.__GLOBAL_VUE_APP, 'STORE_PATH', 'prototype');
      } else {
        set(window.__GLOBAL_VUE_APP, 'STORE_PATH', 'config.globalProperties');
      }

      function getApp() {
        return window.__GLOBAL_VUE_APP;
      }

      function getStore() {
        const app = getApp();
        return get(app, get(app, 'STORE_PATH'));
      }

      Object.defineProperty(window, 'defineVueGlobalProperty', {
        enumerable: true,
        configurable: false,
        writable: false,
        value: function (name, value) {
          set(getStore(), name, value);
        },
      });

      Object.defineProperty(window, 'getVueGlobalProperty', {
        enumerable: true,
        configurable: false,
        writable: false,
        value: function (name, type, handle) {
          if (arguments.length > 2) {
            [name, type, handle] = arguments;
          } else {
            [name, type] = arguments;
            if (typeof type === 'function') {
              handle = type;
            }
          }
          let val = get(getStore(), name);
          if (typeof type === 'string' && type) {
            val = typeof val === type ? val : void 0;
          }
          if (typeof handle === 'function') {
            return val !== void 0 ? handle(val) : void 0;
          }
          return val;
        },
      });
    } catch (e) {
      console.log('vueGlobalProperty.js: ', e);
    }
  },
};
